import { STORAGE_KEYS, URL_CONFIG } from './defines';
import { getCurrentChatId, getChatTitle, setCachedOrderData, getChatImage } from './whatsappHandler';

// 类型声明
interface AuthInfo {
    authorization: string;
    ptoken: string;
}

interface ChatData {
    order_no?: string;
    crmorder_id?: string;
    follow_status?: string;
    customer_info?: any;
    [key: string]: any;
}

// 记录最后一次弹窗时间，用于控制弹窗频率
let lastErrorPopupTime = 0;
const ERROR_POPUP_INTERVAL = 5 * 60 * 1000; // 5分钟，单位毫秒

// 控制弹窗频率的函数
function shouldShowErrorPopup(): boolean {
    const now = Date.now();
    if (now - lastErrorPopupTime > ERROR_POPUP_INTERVAL) {
        lastErrorPopupTime = now;
        return true;
    }
    return false;
}

// 统一处理500错误的函数
function handle500Error(): void {
    if (shouldShowErrorPopup()) {
        alert('服务器错误，请登录ERP重新授权后再尝试');
        window.open(URL_CONFIG.ERP_BASE_URL + '/#/login', '_blank');
    }
}

// 获取认证信息
export async function getAuthInfo(): Promise<AuthInfo> {
    return new Promise((resolve) => {
        chrome.storage.local.get([STORAGE_KEYS.AUTH, STORAGE_KEYS.PTOKEN], (result) => {
            resolve({
                authorization: result[STORAGE_KEYS.AUTH] || '',
                ptoken: result[STORAGE_KEYS.PTOKEN] || ''
            });
        });
    });
}

// 从 chrome.storage.local 获取最后选择的管理员
export async function getLastSelectedManager(): Promise<number> {
    return new Promise((resolve) => {
        chrome.storage.local.get([STORAGE_KEYS.LAST_MANAGER], (result) => {
            resolve(result[STORAGE_KEYS.LAST_MANAGER] || 96);
        });
    });
}

// 保存选择的管理员到 chrome.storage.local
export async function saveLastSelectedManager(managerId: number): Promise<void> {
    return new Promise((resolve, reject) => {
        chrome.storage.local.set({
            [STORAGE_KEYS.LAST_MANAGER]: managerId
        }, () => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve();
            }
        });
    });
}

// 获取聊天订单数据
export async function getChatOrderData(chatId: string): Promise<ChatData | null> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('未获取到认证信息');
        }

        // 获取账户 ID
        const account_id = await getStoredAccountID();
        
        // 获取聊天标题
        const chatTitle = getChatTitle();

        
        const response = await fetch(`https://tools.kikimami.com/crm/api/getwhatsappchatinfo/?_serialized=${chatId}&account_serialized=${account_id}&chattitle=${chatTitle}`, {
            method: 'GET',
            headers: {
                'authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 500) {
            handle500Error();
            return null;
        }

        if (!response.ok) {
            throw new Error('获取订单数据失败');
        }

        const data = await response.json();
        // 返回完整的响应数据，包括可能存在的 ai_reply 字段
        if (data.data) {
            // 如果存在 ai_reply 字段，将其添加到返回的数据中
            if (data.ChatRemind) {
                data.data.ChatRemind = data.ChatRemind;
            }
            return data.data;
        }
        return null;
    } catch (error) {
        console.error('获取订单数据出错:', error);
        return null;
    }
}

// 发送消息到 ERP
export async function sendMessagesToERP(chatId: string, messagesData: any[]): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('未获取到认证信息');
        }

        // 获取账户 ID
        const accountId = await getStoredAccountID();

        const payload = {
            chat_id: chatId,
            account_id: accountId,
            messages: messagesData.map(msg => {
                return {
                    message_id: msg.message_id,
                    timestamp: msg.timestamp,
                    message_from_name: msg.message_from_name,
                    body: msg.body
                };
            })
        };

        const response = await fetch('https://tools.kikimami.com/crm/api/syncwam/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify(payload)
        });

        if (response.status === 500) {
            handle500Error();
            throw new Error('服务器错误，请登录ERP重新授权');
        }

        if (!response.ok) {
            throw new Error('发送消息到 ERP 失败');
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('发送消息到 ERP 出错:', error);
        throw error;
    }
}

// 获取跟进状态
export async function getFollowStatus(): Promise<any> {
    try {
        const authInfo = await getAuthInfo();
        if (!authInfo.authorization || !authInfo.ptoken) {
            throw new Error('未获取到认证信息');
        }

        const response = await fetch('https://tools.kikimami.com/crm/api/getwhatsappfollowstatus/', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            }
        });

        if (response.status === 500) {
            handle500Error();
            throw new Error('服务器错误，请登录ERP重新授权');
        }

        if (!response.ok) {
            throw new Error('获取跟进状态失败');
        }

        const data = await response.json();
        
        // 存储跟进状态
        await new Promise<void>((resolve, reject) => {
            chrome.storage.local.set({ [STORAGE_KEYS.FOLLOW_STATUS]: data.data }, () => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve();
                }
            });
        });
        
        return data;
    } catch (error) {
        console.error('获取跟进状态出错:', error);
        throw error;
    }
}

// 获取提示词列表
export async function fetchAndStorePrompts(authInfo: AuthInfo): Promise<any> {
    try {
        const response = await fetch('https://tools.kikimami.com/crm/api/getprompts/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': authInfo.authorization,
                'ptoken': authInfo.ptoken
            },
            body: JSON.stringify({ t: "whatsapp_prompts" })
        });

        if (response.status === 500) {
            handle500Error();
            throw new Error('服务器错误，请登录ERP重新授权');
        }

        if (!response.ok) {
            throw new Error('获取提示词列表失败');
        }

        const data = await response.json();
        
        // 存储提示词列表
        await new Promise<void>((resolve, reject) => {
            chrome.storage.local.set({ [STORAGE_KEYS.PROMPTS]: data }, () => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve();
                }
            });
        });

        return data;
    } catch (error) {
        console.error('获取提示词列表出错:', error);
        throw error;
    }
}

// 获取存储的账户 ID
export async function getStoredAccountID(): Promise<string> {
    let result = await new Promise<string | null>((resolve) => {
        chrome.storage.local.get([STORAGE_KEYS.ACCOUNT_ID], (res) => {
            resolve(res[STORAGE_KEYS.ACCOUNT_ID] || null); // 修改默认值为null便于判断
        });
    });

    // 当不存在存储值时弹出输入框
    if (!result) {
        result = prompt('请输入WhatsApp账户ID（无需添加@c.us后缀）以86开头:');
        if (!result) return ''; // 用户取消输入
        
        // 存储用户输入的账号
        await chrome.storage.local.set({ 
            [STORAGE_KEYS.ACCOUNT_ID]: result 
        });
    }

    // 自动补全后缀逻辑
    if (result.indexOf('@c.us') === -1) {
        result = result + '@c.us';
        // 更新存储确保包含后缀
        await chrome.storage.local.set({ 
            [STORAGE_KEYS.ACCOUNT_ID]: result 
        });
    }
    
    return result;
}

// 更新存储的账户 ID
export async function updateStoredAccountID(accountId: string): Promise<void> {
    if(accountId.indexOf('@c.us') === -1) {
        accountId = accountId + '@c.us';
    }
    await new Promise<void>((resolve, reject) => {
        chrome.storage.local.set({ [STORAGE_KEYS.ACCOUNT_ID]: accountId }, () => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve();
            }
        });
    });
} 